ko.bindingHandlers.file = {
	init : function(element, valueAccessor, allBindingsAccessor, viewModel) {
		var value = ko.utils.unwrapObservable(valueAccessor());
		var base = '/explorer/images/';
		var src = '';
		if (value.type == 2) {
			src = 'folder.png';
		} else {
			var index = value.name.lastIndexOf('.');
			if (index != -1) {
				var ext = value.name.substring(index + 1);
				src = ext + '.png';
			} else {
				src = 'file.png';
			}
		}
		$(element).height(16);
		$(element).width(16);
		$(element).css('vertical-align', 'middle');
		$(element).attr('src', base + src);
		$(element).attr('onerror', 'this.src="' + base + 'file.png"');
		
		var vm = arguments[4].$root;
		if (value.type == 1 && vm.allowDownload()) {
			var filename = encodeURI(vm.selectedPath() + value.name);
			var url = jsonrpc.uri + '?__cmd__=download&file=' + filename;
			var img = '<img border="0" src="/images/download.png" height="16" width="16" style="vertical-align:middle;" title="Download" />';
			var $d = $('<a href="' + url + '">' + img + '</a>');
			$(element).parent().append($d);
		}
	}
};

function formatFileSize(data) {
	var size = data.size;
	var ret = '-';
	if (size > 0) {
		if (size < 1024) {
			ret = size + ' bytes';
		} else if (size >= 1024 && size < 1024 * 1024) {
			ret = (size / 1024).toFixed(2) + ' KB';
		} else if (size >= 1024 * 1024 && size < 1024 * 1024 * 1024) {
			ret = (size / 1024 / 1024).toFixed(2) + ' MB';
		} else if (size >= 1024 * 1024 * 1024 && size < 1024 * 1024 * 1024 * 1024) {
			ret = (size / 1024 / 1024 / 1024).toFixed(2) + ' GB';
		}
	}
	return ret;
}

function ExplorerViewModel() {
	var self = this;

	self._selectedPath = ko.observableArray([]);
	self.selectedPath = ko.observable('');
	self.type = ko.observable('');
	self.allowDownload = ko.observable(false);
	
	self.listFiles = function() {
		var path = '';
		var file = arguments[0];
		if (file) {
			if (file instanceof ExplorerViewModel) { // Parent Directory
				self._selectedPath.pop();
			} else {
				if (file.type != 2) {
					return;
				}
				self._selectedPath.push(file.name);
			}
			if (self._selectedPath().length > 0) {
				path = self._selectedPath().join('/').replace(/[\\/]+/g, '/');
			}
			self.selectedPath(path);
		}

		jsonrpc.invoke({
			method : 'files',
			params : {
				path : self.selectedPath(),
				type : self.type()
			},
			success : function(data) {
				if (!path) {
					data.result = data.result.reverse();
				}
				
				self.files([]);
				var folderList = [];
				var fileList = [];
				var list = data.result;
				for ( var i in list) {
					if (list[i].type == 2) {
						folderList.push(list[i]);
					} else {
						fileList.push(list[i]);
					}
				}
				self.files(folderList.concat(fileList));
			}
		});
	}

	self.files = ko.observableArray([]);

	self.listFiles();
}
